/*
*/

#include "beam.h"

#include "display.h"
#include "event.h"
#include "form.h"
#include "timer.h"

u32 BeamCont(void){
    BeamOn(beam.key);
    return Timer();
}

void BeamOff(void){
    while(DMA_GetCurrDataCounter(BEAM_DMA)){
	__WFI();
	Display();
    }
}

u32 BeamOn(u8 key){
    TIM_TimeBaseInitTypeDef	b;
    TIM_OCInitTypeDef		i;
    DMA_InitTypeDef		d;

    if(DMA_GetCurrDataCounter(BEAM_DMA))
	return 0;
    if(beam.key!=key){
	if(!Encode(&beam,&keywave[key])){
	    beam.timeout=0;
	    return 0;
	}
	beam.key=key;
    }
    beam.timeout	=120;
    b.TIM_Period	=700;//beam.period;
    b.TIM_Prescaler	=0;
    b.TIM_ClockDivision	=0;
    b.TIM_CounterMode	=TIM_CounterMode_Up;
    b.TIM_RepetitionCounter=beam.repetition;
    TIM_TimeBaseInit(BEAM_TIM,&b);
    i.TIM_OCMode	=TIM_OCMode_PWM1;
    i.TIM_OutputState	=TIM_OutputState_Disable;
    i.TIM_OutputNState	=TIM_OutputNState_Enable;
    i.TIM_Pulse		=0;
    i.TIM_OCPolarity	=TIM_OCNPolarity_Low;
    i.TIM_OCNPolarity	=TIM_OCNPolarity_High;
    i.TIM_OCIdleState	=TIM_OCIdleState_Set;
    i.TIM_OCNIdleState	=TIM_OCIdleState_Reset;
    TIM_OC2Init(BEAM_TIM,&i);
    d.DMA_PeripheralBaseAddr=(u32)&BEAM_TIM->BEAM_CCR;
    d.DMA_MemoryBaseAddr=(u32)beam.wave;
    d.DMA_BufferSize	=8;//beam.head;
    d.DMA_DIR		=DMA_DIR_PeripheralDST;
    d.DMA_PeripheralInc	=DMA_PeripheralInc_Disable;
    d.DMA_MemoryInc	=DMA_MemoryInc_Enable;
    d.DMA_PeripheralDataSize=DMA_PeripheralDataSize_HalfWord;
    d.DMA_MemoryDataSize=DMA_MemoryDataSize_HalfWord;
    d.DMA_Mode		=DMA_Mode_Normal;
    d.DMA_Priority	=DMA_Priority_High;
    d.DMA_M2M		=DMA_M2M_Disable;
    DMA_Init(BEAM_DMA,&d);
    DMA_ITConfig(BEAM_DMA,DMA_IT_TC,ENABLE);
    DMA_Cmd(BEAM_DMA,ENABLE);
    TIM_DMACmd(BEAM_TIM,TIM_DMA_Update,ENABLE);
    TIM_CtrlPWMOutputs(BEAM_TIM,ENABLE);  
    TIM_Cmd(BEAM_TIM,ENABLE);
    return 1;
}

